// src/composables/useScroll.js
import { onMounted, onUnmounted, ref } from 'vue'
import { debounce } from '@/utils'

export function useScroll(target = document.body) {
  const x = ref(0)
  const y = ref(0)
  const direction = ref(null) // 'up'/'down'
  let lastY = 0


  const updatePosition = () => {
    if (target === window) {
      x.value = window.scrollX
      y.value = window.scrollY
    } else {
      x.value = target.scrollLeft
      y.value = target.scrollTop
    }

    // 计算滚动方向
    direction.value = y.value > lastY ? 'down' : 'up'
    lastY = y.value
  }

  // 带防抖的更新
  const debouncedUpdate = debounce(updatePosition, 100)

  onMounted(() => {
    target.addEventListener('scroll', debouncedUpdate, { passive: true })
  })

  onUnmounted(() => {
    target.removeEventListener('scroll', debouncedUpdate)
  })

  return { x, y, direction }
}